package com.dftdla.server.handler;

import com.dftdla.dao.pojo.ChatMsg;
import com.dftdla.dao.service.ChatMsgService;
import com.dftdla.mq.publisher.RabbitMqPublisher;
import com.dftdla.result.ResponseResult;
import com.dftdla.server.message.request.ChatRequestMessage;
import com.dftdla.util.Code;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * @author 14501
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Resource
    private RabbitMqPublisher publisher;
    @Resource
    private ChatMsgService chatMsgService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        msg.setFrom(msg.getUserId());
        ChatMsg chatMsg = new ChatMsg(msg);
        chatMsgService.save(chatMsg);
        ArrayList<Long> list = new ArrayList<>();
        list.add(msg.getTo());
        publisher.sendMsg(list,chatMsg);
        ctx.writeAndFlush(new TextWebSocketFrame(new ResponseResult<>(Code.SUCCESS,chatMsg).toString()));
        log.info("msg:{},已提交发送",chatMsg);
    }
}
